package com.qys.livesMall.anchor.task;

import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.cache.RedisCache;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.YearMonth;


/**
 * 主播收益排名奖励任务（日、月）
 * @author Admin
 */
@Slf4j
@Component
public class IncomeRankAward {

    private final static String REDIS_LOCK_KEY = "IncomeRankAward_lock";

    @Resource
    private H2AnchorService anchorService;
    @Resource
    private RedisCache redisCache;

    @Scheduled(cron = "0 59 23 * * ?") // 每天晚上23点59分执行一次
    public void exc() throws InterruptedException {
        try {
            //获取锁
            boolean lock = redisCache.lock(REDIS_LOCK_KEY, 1, 60);
            if(!lock){
                return;
            }
            log.info("IncomeRankAward start");
            //判断是否最后一天
            LocalDate today = LocalDate.now();
            YearMonth yearMonth = YearMonth.from(today);
            LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();
            if (today.equals(lastDayOfMonth))  {
                log.info("执行主播月收益排名奖励");
                //月末最后一天进行日奖励和月奖励
                anchorService.incomeRankingAward(5);
                anchorService.incomeRankingAward(6);
            } else {
                log.info("执行主播月日收益排名奖励");
                //非月末最后一天进行日奖励
                anchorService.incomeRankingAward(5);
            }
        } catch (Exception e) {
            log.error("error IncomeRankAward:{}", e.getMessage());
        } finally {
            //释放锁
            redisCache.deleteLock(REDIS_LOCK_KEY);
        }
    }
}

